package com.shxy.service.impl;

import com.shxy.dao.EmployeeDao;
import com.shxy.dao.UserDao;
import com.shxy.dao.UserRoleDao;
import com.shxy.entity.Employee;
import com.shxy.entity.User;
import com.shxy.entity.common.enums.RoleEnum;
import com.shxy.entity.user.UserRole;
import com.shxy.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户信息管理器
 */
@Service
public class UserService implements IUserService {
    @Autowired private EmployeeDao employeeDao;
    @Autowired private UserDao userDao;
    @Autowired private UserRoleDao userRoleDao;

    @Override
    public User getUserByIdCard(String idCard) {
        // 1、根据身份证号查询员工信息
        Optional<Employee> op = employeeDao.findByIdCard(idCard);
        if(op.isEmpty()) {
            return null;
        }
        // 2、根据员工获取用户
        return userDao.getUserByEmployee(op.get());
    }

    @Override
    public User getUserById(String id) {
        Optional<User> op = userDao.findById(id);
        if(op.isPresent()) {
            User user = op.get();
            List<UserRole> urs = userRoleDao.findAllByUser(user);
            List<RoleEnum> roles = Arrays.asList(RoleEnum.USER);
            roles.addAll(urs.stream().map(UserRole::getRole).collect(Collectors.toList()));
            user.setRoles(roles);
            return user;
        }
        return null;
    }

    @Override
    public List<User> initUsers() {
        // 1、清空用户表
        userDao.deleteAll();
        // 2、读取全部员工
        List<Employee> employees = employeeDao.findAll();
        // 3、将员工变成用户
        List<User> users = employees.stream().map(emp -> {
            User user = new User();
            user.setEmployee(emp);
            user.setPassword(emp.getIdCard().substring(12));
            user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            return user;
        }).collect(Collectors.toList());

        return userDao.saveAll(users);
    }
}
